const net = require("net");
const knex = require("../DAO/conn")
const conf = require("../config")

const server = net.createServer((clientProc) => {
    console.log("客户端" + id + "已连接" + clientProc.remoteAddress + ":" + clientProc.remotePort);
    clientProc.on("end", () => {
        console.log("客户端" + id + "断开连接");
    });
    clientProc.on("data", (trunk) => {
        console.log(trunk);//显示为Hex字符串
        // console.log(trunk[0].toString(16));//显示为十进制整数data
        var data = JSON.parse(trunk.toString('utf8'));
        console.log(data);
        id = data.id;
        knex('devices').insert({ type: data.type, id: data.id, sn: data.sn, power: data.power, state: data.state, time: data.time }).catch(err => { console.error(err) })
        clientProc.write("{\"message\":\"收到！\"}\r\n");
    })
    clientProc.on("error", (err) => {
        console.error(err)
        console.log("客户端意外断开连接")
    })
    // clientProc.pipe(clientProc);
})

server.on("error", (err) => {
    throw err;
});

server.listen(conf.socketPort, conf.host, () => {
    console.log("socket服务已启动", server.address());
})

var id = "";
module.exports = server;
